package com.qidianit.common.util;

import com.qidianit.common.annotation.DesensitivityAnnotation;

import java.lang.reflect.Field;
import java.util.Arrays;

/**
 * @Author 戴着假发的程序员
 * @Company 起点编程
 * @Description
 * @Time 2024/10/17 上午 10:55
 */
public class DesensitivityUtil {
    public static <T> T desensitization(T t) {
        // 通过反射获取所有的属性
        Class<?> clazz = t.getClass();
        Field[] fields = clazz.getDeclaredFields();
        // 遍历属性
        Arrays.stream(fields).forEach(field -> {
            field.setAccessible(true);// 允许访问私有属性
            // 判断是否有DesensitivityAnnotation注解， 而且属性的类型必须是String
            if (field.isAnnotationPresent(DesensitivityAnnotation.class) && field.getType() == String.class) {
                // 获取注解
                DesensitivityAnnotation annotation = field.getAnnotation(DesensitivityAnnotation.class);
                // 获取注解的值
                String value = annotation.value();
                int length = annotation.length();
                int prefixNoMaskLength = annotation.prefixNoMaskLength();
                int suffixNoMaskLength = annotation.suffixNoMaskLength();
                try {
                    // 获取属性的值
                    String fieldValue = field.get(t).toString();
                    // 脱敏处理
                    String pre = fieldValue.substring(0,prefixNoMaskLength);
                    String suff = fieldValue.substring(fieldValue.length() - suffixNoMaskLength);
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0 ;i < length;i ++){
                        sb.append(value);
                    }
                    // 拼接最终的值
                    field.set(t,pre + sb.toString() + suff);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        return t;
    }
}
